<template>
	<view>
		<view class="goods-list">
		  <view v-for="(good,i) in goodsList" :key="i" @click="gotoDetail(good)">
        <!-- 为my-goods组件绑定good属性的值 -->
        <my-goods :good='good'></my-goods>
      </view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
        //请求参数对象
				queryObj:{
          //查询关键词
          query:'',
          //商品分类的id
          cid:'',
          //页码值
          pagenum:1,
          //每页显示多少条数据
          pagesize:10,         
        },
        //商品列表的数据
        goodsList:[],
        //总数量，用来实现分页
        total:0,
        //是否正在请求
        isLoading:false
        
			}
		},
    onLoad(options) {
      //将页面参数转存到this.queryObj对象
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      // console.log(this.queryObj);
      this.getGoodList()
    },
		methods: {
			async getGoodList(cb){
        //***打开节流阀
        this.isLoading = true
        const {data:res} = await uni.$http.get('api/public/v1/goods/search',this.queryObj)
        //***关闭节流阀
        this.isLoading = false
        //只要数据请求完毕，就立即按需调用cb回掉函数
        cb && cb()
        if(res.meta.status !== 200) return uni.$showMsg()
        // console.log(res);
        //为数据赋值
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
        
      },
      //触底的事件
      onReachBottom(){
        // console.log("触底");
        // console.log(this.queryObj.pagenum);
        //判断是否还有下一页数据
        if(this.queryObj.pagenum * this.queryObj.pagesize >= this.total)
        return uni.$showMsg("数据加载完毕！")
        
        //若数据正在请求其他数据，则不发送额外请求
        if(this.isLoading) return 
        
        //让页码值自增加1
        this.queryObj.pagenum += 1
        //重新获取列表数据
        this.getGoodList()
      },
      
      //下拉刷新的事件
      onPullDownRefresh(){
        //重置关键数据
        this.queryObj.pagenum = 1
        this.total = 0
        this.isLoading = false
        this.goodsList = []
        //重新发起请求
        this.getGoodList(()=>uni.stopPullDownRefresh())
        
      },
      //跳转到商品详情页面
      gotoDetail(good){
        uni.navigateTo({
          url:'/subpkg/goods_detail/goods_detail?goods_id=' + good.goods_id
        })
      }
		}
	}
</script>

<style lang="scss">

</style>
